<template>
  <div class="dist-header-tab" ref="tabsTopCtrl">
    <a-tabs
      v-model="activeKey"
      :style="{ height: '42px', width: '100%' }"
      class="dist-header-tab-top"
      @prevClick="callback"
      @nextClick="callback"
      @edit="onEdit"
      @tabClick="tabClick"
      type="editable-card"
      hide-add
      v-show="true"
    >
      <a-tab-pane
        v-for="pane in tabList"
        :key="pane.key"
        :closable="pane.closable">
        <template slot="tab">
          <span :title="pane.title">{{ pane.title }}</span>
        </template>
      </a-tab-pane>
    </a-tabs>

    <div class="dist-content">
      <keep-alive>
        <router-view v-if="$route.meta.keepAlive !== false" :key="$route.fullPath"></router-view>
      </keep-alive>

      <!--// 非缓存组件跳转页面-->
      <router-view v-if="$route.meta.keepAlive === false" :key="$route.fullPath"></router-view>

      <component
        v-for="item in iframeTabList"
        :key="item.key"
        :is="item.name"
        v-show="$route.fullPath === item.path"
      ></component>
    </div>
  </div>
</template>

<script>

import { mapState } from 'vuex'
import Vue from 'vue'

export default {
  name: 'DistHeaderTab',
  data () {
    return {
      mode: 'top',
      activeKey: '',
      componentsArr: [],
      iframeTabList: [], // 所有的iframeTab
      showTabs: false,
      isTopTabs: true
    }
  },
  props: {
    hideTab: {
      type: Boolean,
      default: false
    }
  },
  components: {},
  created () {
    // 设置iframe页的数组对象
    const componentsArr = this.getComponentsArr()

    if (componentsArr) {
      componentsArr.forEach((item) => {
        Vue.component(item.cName, item.component)
      })
    }
    this.componentsArr = componentsArr
    // 判断当前路由是否iframe页
    this.isOpenIframePage()

    this.showTabs = this.hideTab || false
  },
  mounted () {
    window.addEventListener('resize', () => {
      this.Event.$emit('_RESIZE_TABLE_HEIGHT_')
    })
  },
  computed: {
    ...mapState({
      headerTab: state => state.nav.headerTab
    }),
    tabList () {
      const group = this.$route.meta.group
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      this.activeKey = this.$route.fullPath
      return this.headerTab[group]
    },
    hasOpenComponentsArr () {
      return this.componentsArr.filter(item => item.hasOpen)
    }
  },
  methods: {
    callback (val) {
      console.log(val)
    },
    tabClick (targetKey) {
      this.$router.push({ path: targetKey })
    },
    onEdit (targetKey, action) {
      this[action](targetKey)
    },
    /**
     *移除tab
     * 1、清除state里面的记录
     * 2、清除虚拟dom中的缓存
     * 3、如关闭的是当前页面，则默认打开所有tab的最后一个
     */
    remove (targetKey) {
      const panes = this.tabList.filter(pane => pane.key !== targetKey)
      const currentTab = this.tabList.find(pane => pane.key === targetKey)
      const nextTab = panes[panes.length - 1]
      if (this.tabList.length > 1) {
        this.$store.commit('REMOVE_HEADER_TAB', currentTab)
        if (currentTab.key === this.$route.fullPath) {
          this.$router.push({ path: nextTab.path })
        }
      } else {
        this.$error({
          // title: 'This is an error message',
          content: '只有一个页签时，不允许关闭'
        })
        // this.$store.commit('REMOVE_HEADER_TAB', currentTab)
        // this.$router.push({ name: this.$route.meta.modelId })
      }
      if (currentTab.pageType === 'iframeForm') {
        // 移除iframe缓存
        this.iframeTabList = this.iframeTabList.filter(item => item.path !== currentTab.path)
        return
      }
      if (currentTab.isKeepAlive) {
        // 移除keep-alive缓存
        for (const item of this.$children) {
          if (item.$vnode && item.$vnode.key && item.$vnode.key === currentTab.key) {
            this.clearCache(item, currentTab)
            break
          }
        }
      }
      this.$nextTick(() => {
        this.Event.$emit('_RESIZE_TABLE_HEIGHT_')
      })
    },
    /**
     * 清除缓存
     */
    clearCache (component, tab) {
      let cache
      let keys
      let componentInstance
      const vnode = component.$vnode
      if (vnode && vnode.parent && vnode.parent.componentInstance && vnode.parent.componentInstance.cache) {
        cache = vnode.parent.componentInstance.cache
        keys = vnode.parent.componentInstance.keys
      }
      if (cache[tab.key]) {
        if (keys.length) {
          const index = keys.indexOf(tab.key)
          if (index > -1) {
            keys.splice(index, 1)
          }
        }
        componentInstance = cache[tab.key]
        delete cache[tab.key]
        componentInstance.componentInstance.$destroy()
      }
    },

    isOpenIframePage () {
      const target = this.componentsArr.find(item => {
        return item.name === this.$route.name
      })
      if (!target) return
      const currentRoute = this.$route
      const temp = {
        group: currentRoute.meta && currentRoute.meta.group ? currentRoute.meta.group : '_NO_GROUP_',
        name: target.cName,
        path: currentRoute.fullPath,
        key: target.name + '/' + currentRoute.fullPath,
        isActive: true,
        component: target.component
      }
      let flag = false
      for (const item of this.iframeTabList) {
        if (item.path === temp.path) {
          item.isActive = true
          flag = true
        } else {
          item.isActive = false
        }
      }
      if (!flag) this.iframeTabList.push(temp)
    },
    // 遍历路由的所有页面，把含有iframeComponent标识的收集起来
    getComponentsArr () {
      const routes = this.$store.state.permission.addRouters
      const iframeArr = []
      this.getIframeComponentArr(routes, iframeArr)
      return iframeArr.map((item) => {
        const name = item.name || item.path.replace('/', '')
        return {
          cName: 'iframe' + name,
          name: name,
          path: item.path,
          component: item.iframeComponent, // 组件文件的引用
          meta: item.meta
        }
      })
    },
    /**
     * 获取所有的iframeComponent的路由
     */
    getIframeComponentArr (routes, iframeArr) {
      if (!routes) {
        return
      }
      routes.forEach(item => {
        if (item.iframeComponent) {
          iframeArr.push(item)
        }
        if (item.children) {
          this.getIframeComponentArr(item.children, iframeArr)
        }
      })
    },
    /**
     * 根据key选择tab
     * @param tabKey
     */
    findTab (tabKey) {
      // let key = tabKey.split('//')[1],tab = ''
      // key = `/${key}`
      // const key = tabKey
      let tab = ''
      for (const item of this.tabList) {
        if (item.key === tabKey) {
          tab = item
          break
        }
      }
      return tab
    },
    /**
     * 移除tab，自动移除
     * @param tab
     */
    removeTab (tab) {
      this.remove(tab.key)
    }
  },
  watch: {
    '$route' (to, from) {
      if (to.meta.pageType && to.meta.pageType === 'iframeForm') {
        this.isOpenIframePage()
      }
      if (!to.meta.group || to.meta.group === 'NO_GROUP') {
        this.showTabs = true
      } else {
        this.showTabs = this.hideTab
      }
    },
    'hideTab' (val) {
      this.showTabs = this.hideTab
    }
  }
}
</script>

<style lang="less">
.dist-header-tab {
  height: 100%;
  display: flex;
  flex-direction: column;

  .ant-tabs {
    .ant-tabs-nav-scroll {
      text-align: left;
    }

    .ant-tabs-bar {
      margin: 0;
      margin-top: 2px;
    }
  }

  .dist-content {
    height: calc(100% - 40px);
    flex: 1;
    z-index: 999;
  }
}
</style>
